"""
Check HiAgent Configuration
Verify if all required HiAgent API credentials are configured
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

# Load .env file
from dotenv import load_dotenv
load_dotenv()

from src.llm.hiagent_app.config.hiagent_config import HiAgentConfig


def check_config():
    """Check HiAgent configuration"""

    print("=" * 70)
    print("HiAgent Configuration Check")
    print("=" * 70)

    config = HiAgentConfig()

    # Check each required configuration
    checks = {
        "HOST": config.HOST,
        "ACCESS_KEY": config.ACCESS_KEY,
        "SECRET_KEY": config.SECRET_KEY,
        "ACCOUNT_ID": config.ACCOUNT_ID,
        "WORKSPACE_ID": config.DEFAULT_WORKSPACE_ID,
        "DEFAULT_MODEL_ID": config.DEFAULT_MODEL_ID,
        "DEFAULT_EMBEDDING_MODEL_ID": config.DEFAULT_EMBEDDING_MODEL_ID,
    }

    all_configured = True

    print("\nConfiguration Status:")
    print("-" * 70)

    for key, value in checks.items():
        if value:
            # Mask sensitive values
            if key in ["ACCESS_KEY", "SECRET_KEY"]:
                masked = value[:8] + "..." if len(value) > 8 else "***"
                status = "OK"
                print(f"  {key:25s} : {status:5s} ({masked})")
            else:
                status = "OK"
                print(f"  {key:25s} : {status:5s} ({value})")
        else:
            status = "MISSING"
            print(f"  {key:25s} : {status:5s}")
            all_configured = False

    print("-" * 70)

    if all_configured:
        print("\n[SUCCESS] All required configurations are set!")

        # Test basic connectivity
        print("\n" + "=" * 70)
        print("Testing API Connectivity")
        print("=" * 70)

        try:
            from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient
            client = HiAgentAPIClient(config)

            print("\nAttempting to list datasets...")
            response = client.make_request("ListDatasets", {
                "WorkspaceID": config.DEFAULT_WORKSPACE_ID,
                "PageNumber": 1,
                "PageSize": 1
            })

            total = response.get("Total", 0)
            print(f"\n[SUCCESS] API connection works! Found {total} datasets.")

        except Exception as e:
            print(f"\n[ERROR] API connection failed: {str(e)}")
            print("\nPlease verify your credentials are correct.")
            return False

        return True
    else:
        print("\n[ERROR] Some required configurations are missing!")
        print("\nPlease set the following environment variables in your .env file:")
        print("  - HIAGENT_ACCESS_KEY")
        print("  - HIAGENT_SECRET_KEY")
        print("  - HIAGENT_ACCOUNT_ID")
        print("  - HIAGENT_WORKSPACE_ID")
        print("\nYou can copy from .env.example and fill in your values.")
        return False


if __name__ == "__main__":
    success = check_config()
    sys.exit(0 if success else 1)
